#!/bin/sh
LOG_FILE="/tmp/adminmysql.log"
rm -f /tmp/PIPE1
mkfifo /tmp/PIPE1
cat </tmp/PIPE1 &

rm -f /tmp/PIPE2
mkfifo /tmp/PIPE2
cat >> $LOG_FILE </tmp/PIPE2 &

rm -f /tmp/PIPE0
mkfifo /tmp/PIPE0
tee -a /tmp/PIPE1 >/tmp/PIPE2 </tmp/PIPE0 &

exec 1>/tmp/PIPE0 2>&1

echo ""
echo "#######################################################################"
echo "Lancement: $(date)"
echo "#######################################################################"
SQL_SHOW="show slave status\G"
SQL_SKIP_ERROR="STOP SLAVE;SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;start slave;"

MYSQL_CMD="/usr/bin/mysql $@"

COUNT_YES_REPLIC=$(echo "$SQL_SHOW"| $MYSQL_CMD| grep -ic yes)
EXPECT="2"

i=6
while [[ "$COUNT_YES_REPLIC" != "$EXPECT" && $i -gt 0 ]]; do
        ni=$((7-i))
        echo "Tentative n: $ni/6"
        echo "* Arret de la replication";
        #echo "STOP SLAVE;"| $MYSQL_CMD

        echo "* Acquittement de l'erreur courante"
        #echo "SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;"| $MYSQL_CMD

        echo "* Relance de la replication";
        #echo "START SLAVE;"| $MYSQL_CMD
        echo "Attente de 5 sec."
        sleep 5
        COUNT_YES_REPLIC=$(echo "$SQL_SHOW"| $MYSQL_CMD| grep -ic yes)
        let i--
done


COUNT_YES_REPLIC=$(echo "$SQL_SHOW"| $MYSQL_CMD| grep -ic yes)
echo "$SQL_SHOW"| $MYSQL_CMD
if [ "$COUNT_YES_REPLIC" == "$EXPECT" ]; then
        echo "* Replication ok"
else
        echo "* Replication fail"
fi

rm -f /tmp/PIPE*
